import React, {useEffect, useState} from 'react';
import {Link, useHistory} from "react-router-dom";
import {Modal,List, Button, Toast,ListView} from 'antd-mobile';

import Txt from "../../../components/txt/Txt";

import './userList.less';
import man from '../../../libs/img/user/man.png';
import woman from '../../../libs/img/user/woman.png';
import http from "../../../model/http";

const Item = List.Item;
const Brief = Item.Brief;

const pageType = [
    {t:'查看',p:'/user/edit?type=edit&'},
    {t:'预约',p:'/yuyue?'},
    {t:'开单',p:'/goods/order?'},
]
function Btn({type, item,outUserId,isBindOutUesr}) {
  const history = useHistory();
  const userMsg = async ()=>{
    // 权限判断
    // type > 0 && await http.post('/customer/customerRelationInit',{customerCrmId:item.customerCrmId})
    // history.push(`${pageType[type].p}outUserId=${outUserId}`,item);   //动态跳转页面
     // history.push(`/user/edit?type=edit&outUserId=${outUserId}`,item);  //跳转到编辑页面
      history.push('/user/details?isBind='+isBindOutUesr, item); //跳转到客户详情页面
  }
  return (
    <Button type="primary" size="small" inline onClick={userMsg}>{pageType[type].t}</Button>
  )
}

function UserList({list,type,outUserId,isBindOutUesr,searchValue,isSearch,parentFun,entryIsHome}) {
    const history = useHistory();
    const [dataSource,setDataSource] =useState(new ListView.DataSource({
        rowHasChanged: (row1, row2) => row1 !== row2,
    }))
    const [ pageIndex,setPageIndex] =useState(2)
    const [ isLoading,setIsLoading] =useState(true)
    const [ dataArr,setDataArr] =useState([])
    const [ hasMore,setHasMore] =useState(true)

    useEffect(()=>{

        if(isSearch<1){
            setHasMore(false)
            setDataSource(dataSource.cloneWithRows(list))
        }else {
            setDataSource(dataSource.cloneWithRows(list))
            setPageIndex(2)
            list.length<10? setHasMore(false): setHasMore(true)
            setDataArr(list)
        }

    },[list,isSearch])

    const genData=(ref=false,page=2)=> {
        //获取数据
        http.post('/customer/searchCustomer',{
            // params:searchValue,
            params:searchValue,
            page:page,
            items:10
        }).then(function (res){
            if(res?.result==0){
                const lg = res.data.length;
                if(lg<=0){
                    // Toast.success('没有数据了~',1);
                    setHasMore(false)
                    return false;
                }
                if(ref){
                    setDataSource(dataSource.cloneWithRows(res.data))
                    setHasMore(true)
                    setIsLoading(false)
                    setDataArr(res.data)
                }else{
                    //这里表示上拉加载更多
                    if(lg<10){
                         let concat_arr = dataArr.concat(res.data)
                        setDataSource(dataSource.cloneWithRows(concat_arr))
                        setHasMore(false)
                        setDataArr(concat_arr)
                    }else {
                        let concat_arr = dataArr.concat(res.data)
                        setPageIndex(pageIndex+1)
                        setDataSource(dataSource.cloneWithRows(concat_arr))
                        setIsLoading(false)
                        setDataArr(concat_arr)
                    }
                }
            }else{
                Toast.fail("请求错误",1.5);
            }
        });
    }



    const onEndReached = (event) => {
        if ( !hasMore ) {
            return;
        }
        setIsLoading(true)
        setTimeout(() => {
            genData(false,pageIndex);
        }, 1000);
    };
    const clickRefer =async ()=>{
        parentFun(outUserId)
        searchValue=''
    }
    const bindOutUser =async (customerCrmId,outId)=>{
        const user = JSON.parse(window.localStorage.getItem('user'))
        let ok  = await http.outPost('/customer/updateCustomerDetailBind',{
            crmId: user.managerId,
            hosId: window.localStorage.getItem("hosId") || window.hos.hosId,
            userId: user.userid,
            // userId: 'SG03133', // 暂时写死
            customerCrmId:customerCrmId,
            outUserId:outId
        })
        // console.log("ccccc",ok)
        ok.result === 0 && Toast.success( '绑定成功',1.5,function (){
            parentFun(outUserId)
        })
    }
    const toDeails= async(item,outUserId,isBindOutUesr)=>{ 
        if(history.location.state!=undefined && history.location.state.gotoType == 'billing'){ 
            localStorage.removeItem('billingCartData')
            localStorage.removeItem('billingCartDataID')
            sessionStorage.setItem('getHomeCustomerCrmId',item.customerCrmId)
            history.push(`/billing`,{
                customerCrmId: item.customerCrmId
            }) 

            
            
        }else if(history.location.state!=undefined && history.location.state.gotoType == 'serviceEvaluation'){
            let userInfo = await http.post('/customer/customerDetail',{
                customerCrmId: item.customerCrmId
            })
            if(userInfo.result == 0){  
                history.push(`/medicalElectronNav/qrcode`,{
                    userInfo: userInfo.baseInfo[0]
                })
            }
            

        }else{
            console.log("isBindOutUesr:",isBindOutUesr)
            console.log("outUserId:",outUserId)
            console.log("entryIsHome:",entryIsHome)
            console.log("item:",item)
            history.push(`/user/details?isBind=${isBindOutUesr}&outUserId=${outUserId}&entryIsHome=${entryIsHome}`, item); //跳转到客户详情页面
        }
        
      
    }
    const row = (rowData, sectionID, rowID) => {
        return (
            <div key={rowID} className='userList-row g-flex g-x-between g-mt32'
                 onClick={toDeails.bind(this,rowData,outUserId,isBindOutUesr)}
                 style={{padding: '0.25rem 0.2rem', backgroundColor: '#FFFFFF'}}>
                    <div className=' g-flex' >
                        <img src={rowData.sex=='1'?woman:man} style={{width:'1rem',height:'1rem'}} className='g-round' alt="UserImg"/>
                        <div className='g-ml20 g-f24 g-c-999'>
                            <p className='g-f30 g-c-333 '>
                                <span style={{fontSize:'0.32rem',fontWeight:'bold'}}>{rowData?.customerName}</span>
                            </p>
                            {/*<p className='g-f26 g-mt15'>顾客id：<span className='g-f24'>{rowData?.customerCrmId}</span></p>*/}
                            <p className='g-mt24'>卡号：<span>{rowData?.mzcode}</span></p>
                            <p className='g-mt12' style={{lineHeight:'0.4rem'}}>所属咨询：{rowData?.xcname}</p>
                            <p className='g-mt12' style={{lineHeight:'0.4rem'}}>开发人：{rowData?.dwname}</p>
                            {/*<p className='g-f30 g-mt10'> <span style={{ color: '#FF6E27' }}>{parseInt(rowID) +1}</span></p>*/}
                        </div>
                    </div>
                    <div className='g-flex-col g-f24'>
                      {/*<Btn type={type} item={rowData} outUserId={outUserId} isBindOutUesr={isBindOutUesr}/>*/}
                     {
                         entryIsHome==0&&(
                             rowData?.isBind ===0?( <Button   onClick={(e) =>{
                                     e.stopPropagation()
                                     Modal.alert( '绑定客户信息', '确认绑定吗？', [
                                         { text: '取消'},
                                         { text: '确认', onPress:bindOutUser.bind(this,rowData.customerCrmId,outUserId) },
                                     ])
                                 }} type="primary" size="small" inline >绑定</Button>):
                         ( <Button className='bt-isbind '  disabled={true} type="primary" size="small" inline >已绑定</Button>)
                         )
                     }
                    </div>
            </div>
        );
    };

    return (
        <div className='v-user-search'>
            {
                list.length>0&& (
                <div style={{marginTop:'0.32rem'}}>
                    {/*<button onClick={clickRefer}>111111111111</button>*/}
                    {/*<Txt className='g-p10 g-f24 g-mb10 g-flex g-y-center '>*/}
                    {/*    提醒：共找到<span className='search-count'>{list?.length}</span>位顾客，请确定顾客信息后在绑定此微信号*/}
                    {/*</Txt>*/}
                    <ListView
                        dataSource={dataSource}
                        renderFooter={() => (<div style={{ padding: 30, textAlign: 'center' }}>
                            {
                                !hasMore?'加载完毕，没有更多数据了~':(
                                    isLoading && 'Loading...'
                                )
                            }
                        </div>)}
                        renderRow={row}
                        useBodyScroll
                        onEndReachedThreshold={100}
                        onEndReached={onEndReached}
                        pageSize={10}
                    />
                </div>
                )
            }

        </div>
    )
}
export default UserList;